/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

// module
import Taro, { Component } from '@tarojs/taro';
import { Swiper } from '@tarojs/components';

// project
import { CPage, CContent, CHeader, CFooter, CFloat, CAround, CBetween, CCenter, CRow, CWrap, CLine, CHand, CItemX, CItemY, CText, CLabel, CSvg, CImage, CButton, CColumn } from '../../library/comp';
import { Base64, Gen, Time, Zip, Session, Storage, Toast, Modal} from '../../library/func';
import Icon from '../../project/style/icon';
import Http from '../../project/func/http/http';
import '../../library/style/patch.css';

// 引用组件
import { Addcbtn, Cbtn, Chead, Destop, Editcunit, Ibottom, Ibottomp, Listunitone, Listunittwo, LogoLine, LogoLinep, Tabheader } from '../../project/comp';

/******************************************************************************************
 * Export Class
 ******************************************************************************************/


export default class EditIndex extends Component {
	constructor(props) {
		super(props);

		/**
		 * state
		 */
		this.state = {
			id:this.$router.params.id?this.$router.params.id:0,
			set_title:'点击设置标题',
			set_cover:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542628687189&di=5022ae04443483dd4ebe42484ecfc2c3&imgtype=0&src=http%3A%2F%2Fm.tuniucdn.com%2Ffb2%2Ft1%2FG1%2FM00%2FA7%2F22%2FCii-U1jI-3GIHWSoAAY3TTlDHnoAAI4BQP3s40ABjdl776_w640_h480_c1_t0.jpg',
			data:[],
			post_url:"",
			type:"",
			addactive:-2,
		}



	}


	/*------------------------------------------------------------------------------------
	* 声明周期
	*-----------------------------------------------------------------------------------*/
	componentWillMount () {
		this.getData(this.$router.params.type);
	}	

    componentDidMount() {
		this.getData(this.$router.params.type);
    }

	componentDidShow(){

		if(Session.get("set_title") != null){
			this.setState(
				Session.get("set_title"),()=>{
					Session.set("set_title", null)
				}
			)
		}

		if(Session.get("set_content") != null){

			let data = this.state.data;
			let settype = Session.get("set_content")['settype'];
			if(settype != "add"){
				data[Session.get("set_content")['key']] = Session.get("set_content")['item'];
			}else{
				data.splice(Session.get("set_content")['key'], 0, Session.get("set_content")['item']);
			}
			this.setState({
				data:data,
				addactive:-2,
			},()=>{
				Session.set("set_content", null)
			})
		}
		
	}




	// comn

	/*------------------------------------------------------------------------------------
	 * 事件处理
	 *-----------------------------------------------------------------------------------*/
    // onRedirect
    onRedirect = (url, e)=> {
        wx.redirectTo({
            url: url
        })
    }

    // onNavigate
    onNavigate = (url, e)=> {
		wx.navigateTo({
			url: url
		})
	}
	
	//onNavigateBack
	onNavigateBack(num=1){
		wx.navigateBack({
			delta: num
		})                    
	}


	upload(callback){
		wx.chooseImage({
			count: 1,
			success (res) {
				const tempFilePaths = res.tempFilePaths;
				for(var key in tempFilePaths){
					Http.Upload({
						filePath:tempFilePaths[key],
						success:(res)=>{
							callback(res);
						}
					});
				}
			}
		})		  
	}
	
	//取数据
	getData(type){

		let get_url = "";

		switch(type){
			case "article":
			get_url = 'article/detail.php';
			break;
			case "class":
			get_url = 'class/detail.php';
			break;
			case "activity":
			get_url = 'activity/detail.php';
			break;
		}

		if(this.$router.params.id){
			Http.Loading({
				url:get_url,
				data:{
					id:this.$router.params.id,
				},
				success:(res)=>{
					this.setState({
						id:res.id,
						set_cover:res.object.set_cover,
						data:res.object.set_content,
						set_title:res.set_title,
					},()=>{
						console.log(this.state)
						this.makeSetData(type);
					})
				}
			})

		}else{
			this.makeSetData(type);
		}
	}

	//分类提交
	makeSetData(type){


		let post_url = "";
		switch(type){
			
			//需要提交接口的页面 分类  不需要提交的活动在最后的提交中设置
			case "article":
			if(this.state.id == 0){
				post_url = "article/logic/add.php";
			}else{
				post_url = "article/logic/update.php";
			}
			this.setState({
				type:type,
				post_url:post_url,
			})
			break;
			
			case "class":
			if(this.state.id == 0){
				post_url = "class/logic/add.php";
			}else{
				post_url = "class/logic/update.php";
			}
			this.setState({
				type:type,
				post_url:post_url,
			})
			break;


		}
	}

	//点击添加按钮
	onAdd(val){
		if(val == this.state.addactive){
			this.setState({
				addactive:-2,
			})	
		}else{
			this.setState({
				addactive:val,
			})	
		}
	}

	//删除指定内容
	onDelete(key){
		console.log(this.state.data)
		Modal.confirm(
			"确定删除？","",
			()=>{
				let data = this.state.data;
				data.splice(key, 1);
				this.setState({
					addactive:-2,
					data:data
				})		
			},
			()=>{

			}
		);
	}


	//更换图片的公用方法
	setItemImage(callback){
		this.upload((res)=>{
			console.log(res);
			let data = this.state.data;
			let item = {
				"type": "image",
				"content": res
			};

			callback(data, item);
		})

	}

	//添加图片
	onAddimg(key){
		this.setItemImage((data, item)=>{
			data.splice(key, 0, item);
			this.setState({
				addactive:-2,
				data:data
			},()=>{
				console.log(this.state.data)
			})			
		})
	}

	//修改图片
	onChangeImg(key){
		this.setItemImage((data, item)=>{
			data[key] = item;
			this.setState({
				addactive:-2,
				data:data
			},()=>{
				console.log(this.state.data)
			})			
		})

	}


	//修改封面
	changeCover(){
		this.upload((res)=>{
			this.setState({
				addactive:-2,
				set_cover:res
			})		
		})
	}

	//提交数据
	onSubmit(){

		let id = this.state.id;

		let Ttext = id==0 ? '添加成功' : '编辑成功';

		if(this.$router.params.type == "activity"){

            Session.set("activity_data",{
				set_title:this.state.set_title,
				set_cover:this.state.set_cover,
				set_content:JSON.stringify(this.state.data)
			})

			Taro.navigateBack({ delta: 1 })

		}else{

			Http.post({
				url:this.state.post_url,
				data:{
					id:this.state.id,
					type:"publish",
					set_title:this.state.set_title,
					set_cover:this.state.set_cover,
					set_content:JSON.stringify(this.state.data)
				},
				success:(res)=>{
					Toast.text(Ttext);
					setTimeout(()=>{
						this.onNavigateBack();
					}, 500)
				}
			})
	
		}
	}

	/**
	 * 渲染
	 */
	render() {
		return (
			<CPage>
				<CContent style='height:100vh;'>
					<CColumn class='f1' bg='#f2f2f6' mb='50'>

						{/* 头部封面 */}
						<CColumn class='w1' h='130' bg='#d7d7d7' rel>
							<Image style='width:100%;height:100%;position:absolute;' top='0' left='0' mode='aspectFill'  src={this.state.set_cover} />
							<CHand size='20' color='#fff' mb='15' ml='10' mt='10' rel bold onClick={this.onNavigate.bind(this,'/screen/add/input?type=title&value='+this.state.set_title)} >{ this.state.set_title }</CHand>
							<CHand abs right='10' top='100' size='14' w='74' color='#515151' bg='#fff' ra='8' h='20' x='center' onClick={this.changeCover} >更换封面</CHand>
						</CColumn>

						{/* 默认 添加内容功能 */}
						<Addcbtn 
						class='w1'  
						style='margin-top:20rpx;' 
						showBool={ this.state.addactive == -1 ? true : false} 
						onAdd={ this.onAdd.bind(this,-1) }
						onAddimg={ this.onAddimg.bind(this, 0) }
						onAddtext={ this.onNavigate.bind(this, '/screen/add/input?type=content&key=0&value=') }
						></Addcbtn>


						{/* 循环内容 添加内容 */}
                        {
                            this.state.data.map((item, key) => {
                                return(  
                                    
									item.type=="image"?
									<CColumn bg='#fff' px="15" pt='10'>
										<CHand onClick={ this.onDelete.bind(this, key) } y='center'>
											<CSvg w='15' h='15' mb='2' icon={Icon.lajit} color="#666" ></CSvg>
										</CHand>
										<CHand py='20' onClick={ this.onChangeImg.bind(this, key) }>
											<image src={ item.content } style="width:690rpx"  mode="widthFix"/>
										</CHand>
										<Addcbtn 
										class='w1'  
										style='margin-top:20rpx;' 
										showBool={ this.state.addactive == key ? true : false} 
										onAdd={ this.onAdd.bind(this,key) }
										onAddimg={ this.onAddimg.bind(this, key+1) }
										onAddtext={ this.onNavigate.bind(this, '/screen/add/input?type=content&key='+key+1) }
										></Addcbtn>
									</CColumn>
                                    :
									<CColumn bg='#fff' px='15' pt='10'>
										<CHand onClick={ this.onDelete.bind(this, key) } y='center'>
											<CSvg w='15' h='15' mb='2' icon={Icon.lajit} color="#666" ></CSvg>
										</CHand>
										<CHand size='16' color='#9b9b9b' lh='26' onClick={ this.onNavigate.bind(this, '/screen/add/input?type=content&settype=change&key='+key+"&value="+item.content) }>
										{ item.content }
										</CHand>
										<Addcbtn 
										class='w1'  
										style='margin-top:20rpx;' 
										showBool={ this.state.addactive == key ? true : false} 
										onAdd={ this.onAdd.bind(this,key) }
										onAddimg={ this.onAddimg.bind(this, key+1) }
										onAddtext={ this.onNavigate.bind(this, '/screen/add/input?type=content&key='+key+1) }
										></Addcbtn>
									</CColumn>
                                )
                                
                            })
                        }


						
					</CColumn>

					<CHand class='f1' h="50">
					</CHand>


					<Cbtn text="发布" onDosome={ this.onSubmit }></Cbtn>

				</CContent>
			</CPage>
		);
	}
}

